﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;

namespace Think9.Controllers.Basic
{
    [Area("Com")]
    public class FileManageController : Controller
    {
        private ComService ComService = new ComService();
        private AttachmentService AttachmentService = new AttachmentService();
        private readonly IWebHostEnvironment _webHostEnvironment;

        public FileManageController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        }

        public IActionResult Attachment(string attid, string fwid, string listid, string prcid, string userid)
        {
            string A1 = ""; //公共附件选项? 新建 1有权限2无
            string A2 = ""; //公共附件选项? 下载 1有权限2无
            string A3 = ""; //公共附件选项? 删除 1有权限2无

            AttachmentService.GetFileAuthority(fwid, prcid, ref A1, ref A2, ref A3);
            listid = listid == null ? "0" : listid;
            fwid = fwid == null ? "" : fwid;
            ViewBag.listid = listid;
            ViewBag.fwid = fwid;
            ViewBag.prcid = prcid == null ? "" : prcid;
            ViewBag.userid = userid;
            ViewBag.A1 = A1;
            ViewBag.A2 = A2;
            ViewBag.A3 = A3;

            string attid2 = string.IsNullOrEmpty(attid) ? "" : attid;

            if (attid2 == "")
            {
                if (fwid.StartsWith("bi_"))
                {
                    if (listid != "0")
                    {
                        attid2 = ComService.GetSingle("select AttachmentId  FROM " + fwid.Replace("bi_", "tb_") + " WHERE listid= " + listid);
                    }
                }
                else
                {
                    if (listid != "0")
                    {
                        attid2 = ComService.GetSingle("select AttachmentId  FROM flowrunlist WHERE listid= " + listid);
                    }
                }
            }

            if (string.IsNullOrEmpty(attid2))
            {
                if (fwid.Length > 17)
                {
                    attid2 = fwid.Substring(0, 17) + "_" + System.Guid.NewGuid().ToString("N");
                }
                else
                {
                    attid2 = fwid + "_" + System.Guid.NewGuid().ToString("N");
                }

                if (listid != "0")
                {
                    //这操作可能会重复，但是保险些
                    if (fwid.StartsWith("bi_"))
                    {
                        ComService.ExecuteSql("update " + fwid.Replace("bi_", "tb_") + " set AttachmentId='" + attid2 + "'   WHERE listid= " + listid);
                    }
                    else
                    {
                        ComService.ExecuteSql("update flowrunlist set AttachmentId='" + attid2 + "'   WHERE listid= " + listid);
                    }
                }
            }

            ViewBag.AttachmentId = attid2;

            ViewBag.exts = "xls|xlsx|csv|zip|pdf|doc|docx|png|jpeg|jpg|gif";//限制文件类型

            return View();
        }

        public IActionResult Attlist(string attid, string fwid, string listid, string prcid, string userid)
        {
            string A1 = "1"; //公共附件选项? 新建 1有权限2无
            string A2 = "1"; //公共附件选项? 下载 1有权限2无
            string A3 = "1"; //公共附件选项? 删除 1有权限2无
            AttachmentService.GetFileAuthority(fwid, prcid, ref A1, ref A2, ref A3);

            AttachmentService.GetFileAuthority(fwid, prcid, ref A1, ref A2, ref A3);
            listid = listid == null ? "0" : listid;
            fwid = fwid == null ? "" : fwid;
            ViewBag.listid = listid;
            ViewBag.fwid = fwid;
            ViewBag.prcid = prcid == null ? "" : prcid;
            ViewBag.userid = userid;
            ViewBag.A1 = A1;
            ViewBag.A2 = A2;
            ViewBag.A3 = A3;

            string attid2 = string.IsNullOrEmpty(attid) ? "" : attid;

            if (attid2 == "")
            {
                if (fwid.StartsWith("bi_"))
                {
                    if (listid != "0")
                    {
                        attid2 = ComService.GetSingle("select AttachmentId  FROM " + fwid.Replace("bi_", "tb_") + " WHERE listid= " + listid);
                    }
                }
                else
                {
                    if (listid != "0")
                    {
                        attid2 = ComService.GetSingle("select AttachmentId  FROM flowrunlist WHERE listid= " + listid);
                    }
                }
            }

            if (string.IsNullOrEmpty(attid2))
            {
                if (fwid.Length > 17)
                {
                    attid2 = fwid.Substring(0, 17) + "_" + System.Guid.NewGuid().ToString("N");
                }
                else
                {
                    attid2 = fwid + "_" + System.Guid.NewGuid().ToString("N");
                }

                if (listid != "0")
                {
                    //这操作可能会重复，但是保险些
                    if (fwid.StartsWith("bi_"))
                    {
                        ComService.ExecuteSql("update " + fwid.Replace("bi_", "tb_") + " set AttachmentId='" + attid2 + "'   WHERE listid= " + listid);
                    }
                    else
                    {
                        ComService.ExecuteSql("update flowrunlist set AttachmentId='" + attid2 + "'   WHERE listid= " + listid);
                    }
                }
            }

            ViewBag.AttachmentId = attid2;

            ViewBag.exts = "xls|xlsx|csv|zip|pdf|doc|docx|png|jpeg|jpg|gif";//限制文件类型

            return View();
        }

        public IActionResult PictureUplaod(string tbid, string indexid, string from, string fname)
        {
            string strPath = $"{this._webHostEnvironment.WebRootPath}\\UserImg\\";
            ViewBag.tbid = tbid == null ? "" : tbid;
            ViewBag.indexid = indexid == null ? "" : indexid;
            ViewBag.from = from == null ? "" : from;
            ViewBag.fname = fname == null ? "0.gif" : fname;
            if (ViewBag.fname == "0.gif")
            {
                ViewBag.src = Path.Combine("/images/", "0.gif");
            }
            else
            {
                if (System.IO.File.Exists(strPath + ViewBag.fname))
                {
                    ViewBag.src = Path.Combine("/UserImg/", ViewBag.fname);
                }
                else
                {
                    ViewBag.src = Path.Combine("/images/", "nonexistent.gif");
                }
            }

            return View();
        }

        public IActionResult PictureUplaodGrid(string tbid, string indexid, string id, string strv, string fname, string from)
        {
            string strPath = $"{this._webHostEnvironment.WebRootPath}\\UserImg\\";
            ViewBag.Putbid = tbid == null ? "" : tbid;
            ViewBag.Puindexid = indexid == null ? "" : indexid;
            ViewBag.Puid = id == null ? "" : id;
            ViewBag.Puv = strv == null ? "" : strv.Replace("v", "");
            ViewBag.Pufname = fname == null ? "0.gif" : fname;
            if (ViewBag.fname == "0.gif")
            {
                ViewBag.src = Path.Combine("/images/", "0.gif");
            }
            else
            {
                if (System.IO.File.Exists(strPath + ViewBag.fname))
                {
                    ViewBag.src = Path.Combine("/UserImg/", ViewBag.fname);
                }
                else
                {
                    ViewBag.src = Path.Combine("/images/", "nonexistent.gif");
                }
            }

            ViewBag.Pufrom = from == null ? "" : from;

            return View();
        }

        public IActionResult PictureShow(string id)
        {
            string strPath = $"{this._webHostEnvironment.WebRootPath}\\UserImg\\";
            ViewBag.id = id == null ? "0.gif" : id;
            if (ViewBag.id == "0.gif")
            {
                ViewBag.src = Path.Combine("/images/", "0.gif");
                ViewBag.src2 = Path.Combine("/images/", "0.gif");
            }
            else
            {
                if (System.IO.File.Exists(strPath + ViewBag.id))
                {
                    ViewBag.src = Path.Combine("/UserImg/", ViewBag.id);
                    ViewBag.src2 = Path.Combine("/UserImg/", "_" + ViewBag.id);
                }
                else
                {
                    ViewBag.src = Path.Combine("/images/", "nonexistent.gif");
                    ViewBag.src2 = Path.Combine("/images/", "nonexistent.gif");
                }
            }

            return View();
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImgUplaod(List<IFormFile> file)
        {
            string str = "";
            string imgName = "";
            DataResult<string> rtnResult = new DataResult<string>();
            UploadFileEntity uploadFile = new UploadFileEntity();

            foreach (var formFile in file)
            {
                if (formFile.Length > 0)
                {
                    FileInfo fi = new FileInfo(formFile.FileName);
                    string ext = fi.Extension;
                    var orgFileName = fi.Name;
                    imgName = DateTime.Now.ToString("yyyyMMddhhmmss") + formFile.FileName;

                    string uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\UserImg");
                    var filePath = Path.Combine(uploads, "_" + imgName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }

                    //压缩图片
                    this.ImgCompress(10L, uploads, imgName);
                }
                else
                {
                    str = "添加失败";
                }
            }

            if (str == "")
            {
                uploadFile.code = 0;
                uploadFile.src = Path.Combine("/UserImg/", imgName);
                uploadFile.msg = "上传成功";
                uploadFile.filename = imgName;
                return Json(uploadFile);
            }
            else
            {
                var result = new AjaxResult { state = ResultType.error.ToString(), message = "失败" };
                return Json(result);
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> FileUplaod(string attid, string fwid, string prcid, string listid, string userid, List<IFormFile> file)
        {
            string str = "";
            string fileName = "";
            DataResult<string> rtnResult = new DataResult<string>();
            UploadFileEntity uploadFile = new UploadFileEntity();

            try
            {
                foreach (var formFile in file)
                {
                    if (formFile.Length > 0)
                    {
                        fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + formFile.FileName;

                        string uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\UserFile\\" + attid);
                        var filePath = Path.Combine(uploads, fileName);

                        //创建文件夹-创建前已经做了判断有则不创建
                        Think9.Util.Helper.FileHelper.CreateSuffic(uploads);

                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await formFile.CopyToAsync(stream);

                            FileInfo fInfo2 = new FileInfo(filePath);

                            string length = $"{fInfo2.Length / 1024}KB";

                            AttachmentEntity model = new AttachmentEntity();
                            model.AttachmentId = attid;
                            model.FwId = fwid;
                            model.ListId = int.Parse(listid);
                            model.FwId = fwid;
                            model.PrcsId = string.IsNullOrEmpty(prcid) ? 0 : int.Parse(prcid);
                            model.FullName = fileName;
                            model.AddTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                            model.UserId = userid;

                            model.DocType = fInfo2.Extension;
                            model.AttachmentSort = "";
                            model.TotalSize = length;
                            model.DownloadNumber = 0;

                            AttachmentService.Insert(model);

                            if (model.ListId == 0)
                            {
                                //要将标志位加上，后面再修改
                                Record.AddRecord(userid, listid, fwid, "上传附件-" + fileName, attid);
                            }
                            else
                            {
                                Record.AddRecord(userid, listid, fwid, "上传附件-" + fileName);
                            }
                        }
                    }
                    else
                    {
                        str = "上传失败";
                    }
                }

                if (str == "")
                {
                    uploadFile.code = 0;
                    uploadFile.src = attid;
                    uploadFile.msg = "上传成功";
                    uploadFile.filename = fileName;
                    return Json(uploadFile);
                }
                else
                {
                    var result = new AjaxResult { state = ResultType.error.ToString(), message = "失败" };
                    return Json(result);
                }
            }
            catch (Exception ex)
            {
                return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult GetFileList(PageInfoEntity pageInfo, string attid, string fwid, string prcid, string A2, string A3)
        {
            string strPath = $"{this._webHostEnvironment.WebRootPath}\\UserFile\\";

            pageInfo.field = "id";
            pageInfo.order = "desc";

            long total = 0;
            IEnumerable<dynamic> list = AttachmentService.GetPageByFilter(ref total, null, pageInfo, "where AttachmentId ='" + attid + "'");
            foreach (AttachmentEntity obj in list)
            {
                obj.A2 = A2;
                obj.A3 = A3;
                obj.Src = "";
                if (obj.A2 == "1")
                {
                    obj.Src = Path.Combine("/UserFile/" + attid + "/", obj.FullName);
                }
            }

            var result = new { code = 0, msg = "", count = total, data = list };
            return Json(result);
        }

        [HttpGet]
        public IActionResult Download(string attid, string filename)
        {
            string uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\UserFile\\" + attid);
            var filePath = Path.Combine(uploads, filename);
            if (System.IO.File.Exists(filePath))
            {
                ///定义并实例化一个内存流，以存放图片的字节数组。
                MemoryStream ms = new MemoryStream();
                ///图片读入FileStream
                FileStream f = new FileStream(filePath, FileMode.Open);
                ///把FileStream写入MemoryStream
                ms.SetLength(f.Length);
                f.Read(ms.GetBuffer(), 0, (int)f.Length);
                ms.Flush();
                f.Close();

                var contentType = MimeMapping.GetMimeMapping(filename);
                return File(ms, contentType, filePath);
            }
            else
            {
                return Json("文件不存在");
            }
        }

        /// <summary>
        /// 文件删除
        /// </summary>
        /// <returns></returns>
        public IActionResult DeleteFile(int id, string attid, string fileName)
        {
            string uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\UserFile\\" + attid);
            var fullpath = Path.Combine(uploads, fileName);

            if (System.IO.File.Exists(fullpath))
            {
                System.IO.File.Delete(fullpath);
            }

            AttachmentService.DeleteByWhere("where Id=" + id + "");

            var result = new AjaxResult { state = ResultType.success.ToString(), message = "删除成功" };
            return Json(result);
        }

        //压缩
        private void ImgCompress(long level, string uploads, string imgName)
        {
            Image img = Image.FromFile(Path.Combine(uploads, "_" + imgName));
            ImageFormat imgFormat = img.RawFormat;
            EncoderParameters encoderParams = new EncoderParameters();
            encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, level);
            ImageCodecInfo codecInfo = GetEncoder(imgFormat);

            string savePath = Path.Combine(uploads, imgName);
            img.Save(savePath, codecInfo, encoderParams);
            img.Dispose();
        }

        private ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }
}